﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Linq.Expressions;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using CamlexNET;
using LifeInSharePoint.Common;
using LifeInSharePoint.Common.Base;
using Microsoft.SharePoint;
using System.Web.UI.HtmlControls;


namespace LifeInSharePoint.Blog.Common.WebParts.LISPRecentPosts
{
    [ToolboxItemAttribute(false)]
    public class LISPRecentPosts : BaseWebPart
    {

        #region Private Properties

        private const string POSTLIST = "Pages";
        private const string CONTENTTYPE = "Life In SharePoint Blog Post";
        private string transformedXML = null;
        private bool errorFound = false;
        private string errorMessage = null;

        #endregion

        private string _XSLTPath = "/_layouts/LifeInSharePoint.Blog/xslt/RecentPosts.xslt";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("XSLT Path")]
        [WebDescription("Path the the XSLT")]
        public string XSLTPath
        {
            get { return _XSLTPath; }
            set { _XSLTPath = value; }
        }

        private string _RelSiteUrl = "/blog";
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Rel Site Url")]
        [WebDescription("Rel Site Url")]
        public string RelSiteUrl
        {
            get { return _RelSiteUrl; }
            set { _RelSiteUrl = value; }
        }

        private int _RowLimit = 4;
        [Personalizable(PersonalizationScope.Shared)]
        [WebBrowsable(true)]
        [System.ComponentModel.Category("Life In SharePoint")]
        [WebDisplayName("Row Limit")]
        [WebDescription("Row Limit")]
        public int RowLimit
        {
            get { return _RowLimit; }
            set { _RowLimit = value; }
        }


        protected override void OnInit(EventArgs e)
        {
            this.ChromeType = PartChromeType.None;
            this.ExportMode = WebPartExportMode.All;
            base.OnInit(e);
        }

        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!string.IsNullOrEmpty(XSLTPath))
            {
                processData();
            }
            else
            {
                errorFound = true;
                errorMessage = "XSLT Path is not Defined - Please edit webpart Properties";
            }

        }

        protected override void CreateChildControls()
        {
            if (!errorFound)
            {
                HtmlGenericControl container = new HtmlGenericControl("Div");
                container.InnerHtml = transformedXML;
                this.Controls.Add(container);
            }
            else
            {
                Label errorMsg = new Label();
                errorMsg.Text = errorMessage;
                this.Controls.Add(errorMsg);
            }

        }

        private void processData()
        {
            //Get the SP Web
            using (SPSite siteCollection = new SPSite(SPContext.Current.Site.RootWeb.Url + RelSiteUrl))
            {
                using (SPWeb web = siteCollection.OpenWeb())
                {
                    //Get the List Instance
                    SPList newslist = web.Lists[POSTLIST];

                    //Get a new SPQuery Instance
                    SPQuery workQuery = new SPQuery();
                    workQuery.RowLimit = Convert.ToUInt32(RowLimit);
                    //Create Expressions for the CAMLEx
                    var expressions = new List<Expression<Func<SPListItem, bool>>>();
                    expressions.Add(x => ((string)x["ContentType"]) == CONTENTTYPE);
                    var caml = Camlex.Query().WhereAny(expressions).ToString();

                    workQuery.Query = caml + "<OrderBy><FieldRef Name='Modified' Ascending='False'/></OrderBy>";

                    SPListItemCollection _workItemCollection = newslist.GetItems(workQuery);

                    if (_workItemCollection != null && _workItemCollection.Count > 0)
                    {
                        DataTable PostDT = new DataTable("Post");
                        PostDT.Columns.Add("ID");
                        PostDT.Columns.Add("Title");
                        PostDT.Columns.Add("Excerpt");
                        PostDT.Columns.Add("Image");
                        PostDT.Columns.Add("PublishedDate");
                        PostDT.Columns.Add("Link");
                        PostDT.Columns.Add("CommentCount");
                        PostDT.Columns.Add("TimeAgo");
                        PostDT.Columns.Add("Author");

                        foreach (SPListItem _workItem in _workItemCollection)
                        {

                            SPUser _Author = SPUserHelper.GetSPUser(_workItem, "Modified By");
                            string Title = SPListHelper.GetColumnStringValue(_workItem, "Title");
                            int ID = _workItem.ID;
                            int CommentCount = getCommentCount(ID);
                            string Excerpt = SPListHelper.GetColumnStringValue(_workItem, "LISPPostExcerpt");
                            string RollupImage = SPListHelper.GetColumnStringValue(_workItem, "PublishingRollupImage");
                            DateTime PublishedDate = (DateTime)SPListHelper.GetColumnValue(_workItem, "Modified");
                            string Url = SPListHelper.GetColumnStringValue(_workItem, "EncodedAbsUrl");
                            string TimeAgo = SPStringExtensions.TimeAgo(PublishedDate);
                            PostDT.Rows.Add(ID, Title, Excerpt, RollupImage, PublishedDate, Url, CommentCount, TimeAgo, _Author.Name);

                        }

                        DataSet PostsDS = new DataSet("Posts");
                        PostsDS.Tables.Add(PostDT);
                        string resultXML = PostsDS.GetXml();

                        transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);

                    }
                    else
                    {
                        DataTable PostDT = new DataTable("NoPost");
                        PostDT.Columns.Add("Title");
                        PostDT.Rows.Add ("No Posts Found");
                        DataSet PostsDS = new DataSet("Posts");
                        PostsDS.Tables.Add(PostDT);
                        string resultXML = PostsDS.GetXml();
                        transformedXML = SPWebPartHelper.ConvertXML(resultXML, SPContext.Current.Site.Url + XSLTPath);
                    }
                }
            }
        }

        private int getCommentCount(int PostID)
        {
            int postCount = 0;

            //Get the SP Web
            SPWeb web = SPContext.Current.Site.RootWeb;

            //Get the List Instance
            SPList newslist = web.Lists["Comments"];

            //Get a new SPQuery Instance
            SPQuery workQuery = new SPQuery();
            //Create Expressions for the CAMLEx
            var expressions = new List<Expression<Func<SPListItem, bool>>>();
            expressions.Add(x => ((string)x["LISPCommentPostID"]) == PostID.ToString());
            var caml = Camlex.Query().WhereAny(expressions).ToString();

            workQuery.Query = caml;

            postCount = newslist.GetItems(workQuery).Count;

            return postCount;
        }
    }
}